import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// axios请求拦截器
service.interceptors.request.use(function(config) {
  // 携带token
  const token = store.getters.token
  config.headers.Authorization = 'Bearer ' + token

  return config
}, function(error) {
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use((response) => {
  // 1. 将axios返回的数据解一层壳
  const res = response.data
  const { message, success } = res
  if (!success) {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
  return res
  // console.log(response)
}, (error) => {
  Message.error(error.message)
  return Promise.reject(error)
})

export default service
